package handler

import (
	"cloudDevice2/sampleapi/parser"
	"encoding/binary"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/labstack/echo"
)

func uploadAlarmData(context echo.Context) error {
	payload, err := ioutil.ReadAll(context.Request().Body)
	if err != nil {
		log.Println("read post data failed")
		return context.Blob(http.StatusOK, "text/plain", []byte{0x01})
	}

	if len(payload) < 23 {
		log.Println("data length below 23")
		return context.Blob(http.StatusOK, "text/plain", []byte{0x02})
	}
	deviceBytes := make([]byte, 15)
	prefixBytes := make([]byte, 2)
	lenBytes := make([]byte, 2)
	crcBytes := make([]byte, 2)
	optBytes := make([]byte, 2)
	copy(deviceBytes, payload[:15])
	device := string(deviceBytes)
	log.Println(fmt.Sprintf("device: %s", device))
	start_pos := 15
	for {
		if len(payload) < start_pos+8 {
			log.Println(fmt.Sprintf("data length below %d", start_pos+8))
			return context.Blob(http.StatusOK, "text/plain", []byte{0x02})
		}
		copy(prefixBytes, payload[start_pos:start_pos+2])
		if prefixBytes[0] != 0x44 && prefixBytes[1] != 0x54 {
			log.Println(fmt.Sprintf("invalid data header at %d", start_pos))
			return context.Blob(http.StatusOK, "text/plain", []byte{0x03})
		}
		copy(lenBytes, payload[start_pos+2:start_pos+4])
		length := int(lenBytes[1])*0x100 + int(lenBytes[0])
		copy(crcBytes, payload[start_pos+4:start_pos+6])
		copy(optBytes, payload[start_pos+6:start_pos+8])

		if len(payload) < start_pos+8+length {
			log.Println(fmt.Sprintf("data length below %d", start_pos+8+length))
			return context.Blob(http.StatusOK, "text/plain", []byte{0x02})
		}
		pbPayload := payload[start_pos+8 : start_pos+8+length]
		opt := binary.LittleEndian.Uint16(optBytes)
		if opt == 0x12 {
			parser.ProceedAlarmV2(pbPayload)
		}
		start_pos += 8 + length
		if len(payload) == start_pos {
			//just read to the end and no extra byte leave
			break
		}
	}
	return context.Blob(http.StatusOK, "text/plain", []byte{0x00})
}
